<template>
  <div class="main-container">
    <div class="page-title header">
      能碳监控
      <div>
        <el-select style="width: 150px" v-model="selectedArea" placeholder="请选择区域">
          <el-option v-for="item in areaOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
    </div>

    <div class="carbon-monitoring">
      <div class="overview-cards">
        <!-- 骨架屏 -->
        <template v-if="loading">
          <el-card v-for="i in 4" :key="i" class="overview-card">
            <el-skeleton animated>
              <template #template>
                <div class="card-content">
                  <div class="card-header">
                    <el-skeleton-item variant="text" style="width: 50%" />
                    <el-skeleton-item variant="text" style="width: 20%" />
                  </div>
                  <div class="value">
                    <div class="carbon-value">
                      <el-skeleton-item variant="h3" style="width: 80%" />
                    </div>
                    <div class="sc-value">
                      <el-skeleton-item variant="text" style="width: 60%" />
                    </div>
                  </div>
                </div>
              </template>
            </el-skeleton>
          </el-card>
        </template>

        <!-- 实际内容 -->
        <template v-else>
          <el-card v-for="(item, index) in overviewData" :key="index" class="overview-card">
            <div class="card-content">
              <div class="card-header">
                <span class="title">{{ item.title }}</span>
                <span class="rate" :class="item.trend">{{ item.rate }}</span>
              </div>
              <div class="value">
                <div class="carbon-value">
                  <AnimatedNumber suffix="吨CO₂" :value="item.co2Value" />
                </div>
                <div class="sc-value">
                  <AnimatedNumber size="medium" suffix="吨" :value="item.scValue" />
                  标准煤
                </div>
              </div>
            </div>
          </el-card>
        </template>
      </div>
    </div>

    <el-row :gutter="16" class="charts-container" style="flex-grow: 1" v-loading="loading">
      <el-col style="height: 100%" :span="24">
        <el-card style="display: flex; flex-direction: column; height: 100%" body-style="flex: 1">
          <template #header>
            <span>碳排放趋势分析</span>

            <el-button @click="toggleView" type="primary" style="margin-right: 12px;">
              <template #icon>
                <i :class="isTableView ? 'fa fa-line-chart' : 'fa fa-table'"></i>
              </template>
              {{ isTableView ? '切换为图表' : '切换为表格' }}
            </el-button>
            <ChartSelect v-if="!isTableView" :view-type="['chartTypes']" chart-id="water" v-model="chartState" />

            <el-button v-else type="primary" @click="exportEvent">
              <template #icon>
                <i class="fa fa-download"></i>
              </template>
              导出表格
            </el-button>
          </template>

          <BaseChart v-if="!isTableView" :options="trendChartOptions" />

          <div v-else>
            <!-- 合并后的碳排放表格 -->
            <vxe-table ref="tableRef" :data="combinedTableData" :column-config="{ resizable: true }" stripe>
              <vxe-column field="month" title="月份" width="120"></vxe-column>
              <vxe-column field="total" title="总碳排放(吨)"
                :formatter="({ cellValue }) => formatNumber(cellValue)"></vxe-column>
              <vxe-column field="elec" title="电力碳排放(吨)"
                :formatter="({ cellValue }) => formatNumber(cellValue)"></vxe-column>
              <vxe-column field="water" title="水资源碳排放(吨)"
                :formatter="({ cellValue }) => formatNumber(cellValue)"></vxe-column>
              <vxe-column field="gas" title="天然气碳排放(吨)"
                :formatter="({ cellValue }) => formatNumber(cellValue)"></vxe-column>
            </vxe-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import BaseChart from "@/components/chart/BaseChart.vue";
import AnimatedNumber from "@/components/animate/AnimatedNumber.vue";
import { ref, watchEffect, computed } from "vue";
import { useCompanyStore } from "@/stores/company";
import { useCarbonStore } from "@/stores/carbon";
import dayjs from "dayjs";
import { handleError } from "@/utils/handleError";
import { useAreaStore } from "@/stores/area";
import ChartSelect from "../WaterData/WaterDataCenter/ChartAnalysis/components/components/ChartSelect.vue";
import { watch } from "vue";

const loading = ref(false);
const companyStore = useCompanyStore();
const carbonStore = useCarbonStore();
const areaStore = useAreaStore();
const selectedArea = ref("overview");

// 添加对区域变化的监听
watch(selectedArea, () => {
  getCarbonData();
});
const chartState = ref({
  chartType: "line",
});
//折标煤系数
const conversionFactor = 0.68;

//表格ref
const tableRef = ref(null);

// 导出表格
const exportEvent = () => {
  const $table = tableRef.value;
  if ($table) {
    $table.exportData({
      filename: '碳排放数据明细',
      type: 'xlsx'
    });
  }
};

async function getCarbonData() {
  try {
    loading.value = true;
    const companyId =
      selectedArea.value !== "overview" ? 0 : companyStore.currentCompany.id;
    const requestParams = {
      id: companyId,
      start_time: dayjs().startOf("year").valueOf(),
      end_time: dayjs().subtract(5, 'minute').valueOf(),
      interval: "month",
    };

    if (selectedArea.value !== "overview") {
      requestParams.area_id = selectedArea.value;
    }

    await carbonStore.fetchCarbonData(requestParams);
  } catch (error) {
    handleError(error, "获取碳排放数据失败");
  } finally {
    loading.value = false;
  }
}

const isTableView = ref(false);

const toggleView = () => {
  isTableView.value = !isTableView.value;
};

const formatNumber = (value, decimals = 2) => {
  if (value === null || value === undefined) return '-';
  return Number(value).toFixed(decimals);
};

// 合并后的表格数据
const combinedTableData = computed(() => {
  const monthlyData = carbonStore.carbonStatistics.monthlyData;

  return monthlyData.map(item => {
    const elec = Number(item.usage.elec || 0) * conversionFactor;
    const water = Number(item.usage.water || 0) * conversionFactor;
    const gas = Number(item.usage.gas || 0) * conversionFactor;
    const total = elec + water + gas;

    return {
      month: dayjs(item.startTime).format('YYYY-MM'),
      total: total,
      elec: elec,
      water: water,
      gas: gas
    };
  });
});

// 监听公司变化，重置区域选择
watch(
  () => companyStore.currentCompany,
  () => {
    selectedArea.value = "overview";
    getCarbonData();
  },
  { immediate: true }
);

const areaOptions = computed(() => {
  let areaOptions = areaStore.areas.map((item) => ({ value: item.id, label: item.name }))
  return ([
    { value: "overview", label: "总览" },
    ...areaOptions
  ])
});

const overviewData = computed(() => {
  const stats = carbonStore.carbonStatistics;

  function toCO2(val) {
    return val * conversionFactor;
  }

  const totalSC = stats.yearlyTotal;
  const elecSC = stats.currentYear.elec;
  const waterSC = stats.currentYear.water;
  const gasSC = stats.currentYear.gas;

  return [
    {
      title: "本年总碳排放",
      scValue: totalSC,
      co2Value: toCO2(totalSC),
      rate: `${stats.growthRates.total}%`,
      trend: Number(stats.growthRates.total) > 0 ? "up" : "down",
    },
    {
      title: "电力碳排放",
      scValue: elecSC,
      co2Value: toCO2(elecSC),
      rate: `${stats.growthRates.elec}%`,
      trend: Number(stats.growthRates.elec) > 0 ? "up" : "down",
    },
    {
      title: "水资源碳排放",
      scValue: waterSC,
      co2Value: toCO2(waterSC),
      rate: `${stats.growthRates.water}%`,
      trend: Number(stats.growthRates.water) > 0 ? "up" : "down",
    },
    {
      title: "天然气碳排放",
      scValue: gasSC,
      co2Value: toCO2(gasSC),
      rate: `${stats.growthRates.gas}%`,
      trend: Number(stats.growthRates.gas) > 0 ? "up" : "down",
    },
  ];
});

const trendChartOptions = computed(() => {
  const monthlyData = carbonStore.carbonStatistics.monthlyData;

  const xAxisData = monthlyData.map((item) =>
    dayjs(item.startTime).format("YYYY-MM")
  );

  const totalCarbonMonthly = monthlyData.map((item) => {
    const elec = Number(item.usage.elec || 0);
    const water = Number(item.usage.water || 0);
    const gas = Number(item.usage.gas || 0);
    const totalSC = elec + water + gas;
    return Number((totalSC * conversionFactor).toFixed(2));
  });

  return {
    xAxisData,
    yAxisUnit: "吨",
    series: [
      {
        name: "碳排放",
        type: chartState.value.chartType,
        data: totalCarbonMonthly,
      }
    ],
  };
});
</script>

<style lang="scss">
.main-container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.carbon-monitoring {
  .overview-cards {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: var(--gap-normal);
    margin-bottom: var(--gap-normal);

    .overview-card {
      .card-content {
        .card-header {
          display: flex;
          justify-content: space-between;
          margin-bottom: 16px;

          .title {
            color: #909399;
            font-size: 14px;
          }

          .rate {
            font-size: 14px;

            &.up {
              color: #f56c6c;
            }

            &.down {
              color: #67c23a;
            }
          }
        }

        .value {
          display: flex;
          flex-direction: column;

          .carbon-value {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 8px;
          }

          .sc-value {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }
}

.charts-container {
  display: flex;
  flex-direction: row;
  flex-grow: 1;
}
</style>